package com.deram.ctin.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;

/**
 * @author zhangcm
 * @version 1.0, 2017/9/25
 */
public class FreeMarkerUtils {

    private FreeMarkerUtils(){}

    public static String createHtml(Configuration config, String templatePath, Object dataModel){
        StringWriter writer = new StringWriter();
        write(config, templatePath, dataModel, writer);
        return writer.toString();
    }

    public static InputStream createInputStream(Configuration config, String templatePath, Object dataModel) {
        StringWriter writer = new StringWriter();
        write(config, templatePath, dataModel, writer);
        try {
            return new ByteArrayInputStream(writer.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static void write(Configuration config, String templatePath, Object dataModel, Writer out){
        try {
            Template template = config.getTemplate(templatePath);
            template.process(dataModel, out);
            out.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
